package com.dhh.sky.activity;

import java.io.File;
import java.util.List;
import com.dhh.sky.R;
import com.dhh.sky.util.FileViewer;
import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CameraUploadActivity extends Activity{
    private ActionBar actionBar;
	private SharedPreferences sp;
    private DataUpdateReceiver dataUpdateReceiver;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.camera_upload); 

		sp = getSharedPreferences("camera_upload", 0);
        initActionBar();
        initView();
        initUpload();
	}
	
	private void initUpload(){
		dataUpdateReceiver = new DataUpdateReceiver();
		IntentFilter intentFilter = new IntentFilter("CameraUpload");
		registerReceiver(dataUpdateReceiver, intentFilter);
		
		new CheckPhotosTask().execute(new String[]{});
		
	}
	
	private void initView(){
		ProgressBar bar = (ProgressBar) this.findViewById(R.id.cam_progress);
		bar.setMax(100);
		bar.setProgress(60);
	}
	
	private void initActionBar(){
		actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(this.getString(R.string.navigate_camera));
		actionBar.setHomeAction(new HomeAction());
	}
	
	
	private class HomeAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_home_arrow;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
			SlideoutActivity.prepare(CameraUploadActivity.this, R.id.inner_content, width);
			startActivity(new Intent(CameraUploadActivity.this,MenuActivity.class));
			overridePendingTransition(0, 0);
	    }
	}
	
	private boolean isMyServiceRunning() {
	    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
	    
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if ("com.dhh.sky.activity.CameroUploadService".equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}
	
	private class CheckPhotosTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			if(!isMyServiceRunning()){
				// check whether there are photos to update
				boolean isNew = false;
				File rootsd = Environment.getExternalStorageDirectory();
				File dcim = new File(rootsd.getAbsolutePath() + "/DCIM");
				List<File> files = FileViewer.getListFiles(dcim.getAbsolutePath());
				for(File file : files){
					String rec = sp.getString(file.getAbsolutePath(),null);
					if(rec == null){
						isNew = true;
						break;
					}
				}
				
				if(isNew){
					Intent uploadIntent = new Intent(CameraUploadActivity.this, CameroUploadService.class);
					startService(uploadIntent);
				}else{
					Message msg = initViewHandler.obtainMessage();		
					Bundle data = msg.getData();
					data.putInt("status", 1);
					msg.setData(data);
					initViewHandler.sendMessage(msg);
				}
			}else{
				Message msg = initViewHandler.obtainMessage();		
				Bundle data = msg.getData();
				data.putInt("status", 2);
				msg.setData(data);
				initViewHandler.sendMessage(msg);
			}
			
			return "All Done!";
		}
	}
	
	private Handler initViewHandler = new Handler() {
		@Override
        public void handleMessage(Message msg) { 			
			Bundle data = msg.getData();
			int status = data.getInt("status");
			if(status==1){
				CameraUploadActivity.this.findViewById(R.id.cam_list_init).setVisibility(View.GONE);
				CameraUploadActivity.this.findViewById(R.id.cam_list_upload).setVisibility(View.GONE);
				CameraUploadActivity.this.findViewById(R.id.cam_list_ok).setVisibility(View.VISIBLE);
			}else if(status==2){
				CameraUploadActivity.this.findViewById(R.id.cam_list_init).setVisibility(View.VISIBLE);
				CameraUploadActivity.this.findViewById(R.id.cam_list_upload).setVisibility(View.GONE);
				CameraUploadActivity.this.findViewById(R.id.cam_list_ok).setVisibility(View.GONE);
			}
		}
	};
	
	
	
	private class DataUpdateReceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	int max = intent.getExtras().getInt("max");
	    	int current = intent.getExtras().getInt("current");
	    	String name = intent.getExtras().getString("name");
	    	String path = intent.getExtras().getString("path");
	    	Message msg = updateHandler.obtainMessage();
	    	Bundle data = new Bundle();
	    	data.putInt("max", max);
	    	data.putInt("current", current);
	    	data.putString("name", name);
	    	data.putString("path", path);
	    	msg.setData(data);
	    	updateHandler.sendMessage(msg);
	    }
	}
	
	private int calculateSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int size = 1;

	    if (height > reqHeight || width > reqWidth) {
	        if (width > height) {
	        	size = Math.round((float)height / (float)reqHeight);
	        } else {
	        	size = Math.round((float)width / (float)reqWidth);
	        }
	    }
	    return size;
	}
	
	private Bitmap decodeBitmap(File file, int reqWidth, int reqHeight) {
	    final BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(file.getAbsolutePath(), options);

	    // Calculate inSampleSize
	    options.inSampleSize = calculateSize(options, reqWidth, reqHeight);

	    // Decode bitmap with inSampleSize set
	    options.inJustDecodeBounds = false;
	    return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
	}
	
	private Handler updateHandler = new Handler() {
		@Override
        public void handleMessage(Message msg) { 
			LinearLayout uploadList = (LinearLayout) CameraUploadActivity.this.findViewById(R.id.cam_list_upload);
			LinearLayout okList = (LinearLayout) CameraUploadActivity.this.findViewById(R.id.cam_list_ok);
			LinearLayout initList = (LinearLayout) CameraUploadActivity.this.findViewById(R.id.cam_list_init);
        	int max = msg.getData().getInt("max");
        	int current = msg.getData().getInt("current");
        	String title = msg.getData().getString("name");
        	String path = msg.getData().getString("path");
        	ProgressBar bar = (ProgressBar) CameraUploadActivity.this.findViewById(R.id.cam_progress);
			bar.setMax(max);
			bar.setProgress(current);
			
			initList.setVisibility(View.GONE);
			if(max==current){
				uploadList.setVisibility(View.GONE);
				okList.setVisibility(View.VISIBLE);
			}else{
				uploadList.setVisibility(View.VISIBLE);
				okList.setVisibility(View.GONE);
				
				TextView name = (TextView) CameraUploadActivity.this.findViewById(R.id.cam_photo_title);
				TextView left = (TextView) CameraUploadActivity.this.findViewById(R.id.cam_left);
				ImageView img = (ImageView) CameraUploadActivity.this.findViewById(R.id.cam_img);
				
				name.setText(title);
				left.setText((max-current)+CameraUploadActivity.this.getString(R.string.msg_photo_left));
				
				File file = new File(path);
				if(file.exists()){
					img.setImageBitmap(decodeBitmap(file,160,160));
				}
			}
		}
	};
}
